package com.fei.BYSJ.utils;

import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;


public class BeanUtils {
    public  static Map<String,Object> Obj2Map(Object obj) throws Exception{
        Map<String,Object> map=new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for(Field field:fields){
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }
    public static Object map2Obj(Map<String,Object> map,Class<?> clz) throws Exception{
        Object obj = clz.newInstance();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for(Field field:declaredFields){
            int mod = field.getModifiers();
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                continue;
            }
            field.setAccessible(true);
            String val = (String)map.get(field.getName());
            if(StringUtils.isEmpty(val))
                continue;
            if(field.getType().equals(Integer.class)){
                field.set(obj, Integer.parseInt(val));
            }else if(field.getType().equals(Double.class)){
                field.set(obj, Double.parseDouble(val));
            }else{
                field.set(obj,  val);
            }
        }
        return obj;
    }
}
